package com.kb.design.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.design.common.ApiResponse;
import com.kb.design.constant.Constants;
import com.kb.design.dto.CustomContactInfo;
import com.kb.design.dto.DesignOrderDTO;
import com.kb.design.dto.DesignOrderDetailDTO;
import com.kb.design.entity.*;
import com.kb.design.enums.DesignStatus;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CrmService;
import com.kb.design.service.DesignFileService;
import com.kb.design.service.DesignOrderService;
import com.kb.design.util.CommonUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;

@Service
@DS("slave-1")
public class DesignOrderServiceImpl extends ServiceImpl<DesignOrderMapper, DesignOrder> implements DesignOrderService {
    @Resource
    private DesignOrderMapper designOrderMapper;
    @Resource
    private CrmService crmService;
    @Resource
    private DesignFileService designFileService;
    @Resource
    private CustomContactMapper customContactMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Autowired
    private DesignProgressMapper designProgressMapper;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;
    @Value("${ERP.deliveryUrl}")
    private String deliveryUrl;

    // 实现 CRUD 方法
    @Override
    public boolean saveDesignOrder(DesignOrder designOrder) {
        return save(designOrder);
    }

    @Override
    public boolean updateDesignOrder(DesignOrder designOrder) {
        return updateById(designOrder);
    }

    @Override
    public boolean deleteDesignOrder(Long id) {
        return removeById(id);
    }

    @Override
    public DesignOrder getDesignOrderById(Long id) {
        return getById(id);
    }

    @Override
    public Page<DesignOrderDTO> queryByPage(DesignOrderDTO designOrder) {
        Page<DesignOrderDTO> page = new Page<>(designOrder.getPage(), designOrder.getPerPage());
        //orderDateSearch 时间用,号拼接 拆成startDate endDate
        try {
            if (designOrder.getOrderDateSearch() != null && !designOrder.getOrderDateSearch().isEmpty()) {
                String[] split = designOrder.getOrderDateSearch().split(",");
                designOrder.setStartDate(DateUtils.parseDate(split[0], "yyyy-MM-dd"));
                designOrder.setEndDate(DateUtils.parseDate(split[1], "yyyy-MM-dd"));
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return designOrderMapper.queryByPage(page, designOrder);
    }

    @Override
    public Page<DesignOrder> listByParameters(DesignOrderDTO designOrder) {
        Page<DesignOrder> page = new Page<>(designOrder.getPage(), designOrder.getPerPage());
        LambdaQueryWrapper<DesignOrder> wrapper = Wrappers.lambdaQuery();
        if (designOrder.getStatus() != null) {
            wrapper.eq(DesignOrder::getStatus, designOrder.getStatus());
//            wrapper.like(DesignOrder::getCustomerCode, designOrder.getCustomerCode());
            wrapper.like(StringUtils.isNotBlank(designOrder.getCustomerCode()),
                    DesignOrder::getCustomerCode,
                    "%" + designOrder.getCustomerCode() + "%");
            wrapper.like(StringUtils.isNotBlank(designOrder.getFileName()),
                    DesignOrder::getFileName,
                    "%" + designOrder.getFileName() + "%");
        }
        return designOrderMapper.selectPage(page, wrapper);
    }

    @Override
    public DesignOrderDetailDTO getDetailInfo(DesignOrderDTO designOrder) {
        //业务员信息
        DesignOrderDetailDTO designOrderDetailDTO = new DesignOrderDetailDTO();
//        if (designOrder.getOrderId() != null) {
        if (StringUtils.isNotBlank(designOrder.getSalesCode())){
            designOrderDetailDTO = crmService.querySaleInfo(designOrder.getSalesCode());
        }
            //查询客户联系人  先查询本地有没数据 无 再查crm
            LambdaQueryWrapper<CustomContact> wrapper = Wrappers.lambdaQuery(CustomContact.class);
            if (Objects.nonNull(designOrder.getOrderId())) {
                wrapper.eq(CustomContact::getOrderId, designOrder.getOrderId());
            } else {
                wrapper.eq(CustomContact::getProjectId, designOrder.getProjectId());
            }
            wrapper.last("limit 1");
            CustomContact customContact = customContactMapper.selectOne(wrapper);
            BeanUtil.copyProperties(customContact, designOrderDetailDTO);
            if (customContact == null) {
                List<CustomContactInfo> infoList = crmService.queryCustomContactInfo(designOrder.getCustomerCode());
                if (infoList.size() > 1) {
                    StringBuilder customerContact = new StringBuilder();
                    StringBuilder customerPhone = new StringBuilder();
                    StringBuilder customerEmail = new StringBuilder();
                    for (CustomContactInfo customContactInfo : infoList) {
                        //把customerContact字段所有值拼接
                        customerContact.append(customContactInfo.getCustomerContact()).append("; ");
                        customerPhone.append(customContactInfo.getCustomerPhone()).append(";");
                        customerEmail.append(customContactInfo.getCustomerEmail()).append(";");

                    }
                    designOrderDetailDTO.setCustomerContact(customerContact.toString());
                    designOrderDetailDTO.setCustomerPhone(customerPhone.toString());
                    designOrderDetailDTO.setCustomerEmail(customerEmail.toString());
                }
                if (infoList.size() == 1) {
                    designOrderDetailDTO.setCustomerContact(infoList.get(0).getCustomerContact());
                    designOrderDetailDTO.setCustomerPhone(infoList.get(0).getCustomerPhone());
                    designOrderDetailDTO.setCustomerEmail(infoList.get(0).getCustomerEmail());
                }
            }
//        }

        //查询客户信息
        if (designOrder.getOrderId() != null) {
            DesignOrder designOrderInfo = designOrderMapper.queryById(designOrder.getOrderId());
            //查询封装主管信息
            DesignResponsiblePerson designResponsiblePerson = responsiblePersonMapper.queryByOrderId(designOrder.getOrderId());
            if (designResponsiblePerson != null) {
                designOrderDetailDTO.setPackageCompetent(designResponsiblePerson.getResponsiblePersonName());
                designOrderDetailDTO.setDeptName(designResponsiblePerson.getDeptName());
            }

            BeanUtil.copyProperties(designOrderInfo, designOrderDetailDTO);
        } else {
            //根据项目id查询项目数据 针对未下单数据

        }
        //查询项目信息
        if (designOrder.getProjectId() != null) {
            DesignProject designProject = projectMapper.selectById(designOrder.getProjectId());
            if (designProject.getDesignDepartments() == null) {
                designProject.setDesignDepartments(designProject.getPageDepartments());
            }
            BeanUtil.copyProperties(designProject, designOrderDetailDTO);
        }
        return designOrderDetailDTO;
    }

    @Override
    public boolean designOrderService(Integer date) {
        //发送get请求 192.168.20.50:8088/pcbaOrder/ERP2DesignCooperate
//        String url = "http://192.168.20.50:8088/pcbaOrder/ERP2DesignCooperate?date="+date;
        String url = "http://192.168.10.33:8088/pcbaOrder/ERP2DesignCooperate?date=" + date;
        HttpRequest response = HttpUtil.createGet(url);
        if (response.execute().getStatus() == HttpStatus.HTTP_OK) {
            JSONObject jsonObject = JSONObject.parseObject(response.execute().body());
            return jsonObject.getBoolean("data");

        }
        return false;
    }

    @Override
    public boolean cancelOrder(DesignOrderDTO designOrder) {
        CommonUtil.webLog("DesignOrderServiceImpl.cancelOrder", designOrder);
        //更新订单状态
        if (designOrder.getOrderNo() != null) {
            //todo 判断是否生成项目
            DesignOrder order = designOrderMapper.selectOne(Wrappers.lambdaQuery(DesignOrder.class).eq(DesignOrder::getOrderNo, designOrder.getOrderNo()).last("limit 1"));
            if (order != null && order.getStatus() == 1) {
                System.out.println("订单已生成项目");
                return designOrderMapper.delByOrderNo(order.getOrderNo()) > 0;
            }
            //消息推送给客服
            com.kb.util.MessageUtil.sentMessage("23988,25629", "您好，有设计订单取消，订单号：" + designOrder.getOrderNo() + "，请确认是否需要取消项目", "订单取消通知");
            return designOrderMapper.updateDesignOrder(designOrder.getOrderNo(), 3) > 0;

        }
        return false;
    }

}